<?php

namespace app\admin\controller;
use think\Lang;
/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 会员等级折扣控制器
 */
class  Promotionmgdiscount extends AdminControl
{
    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        Lang::load(APP_PATH . 'admin/lang/'.config('default_lang').'/promotionmgdiscount.lang.php');
        //自动开启会员等级折扣
        if (intval(input('param.mgdiscount_allow')) === 1) {
            $config_model = model('config');
            $update_array = array();
            $update_array['mgdiscount_allow'] = 1;
            $config_model->editConfig($update_array);
        }
    }
    

    /**
     * 店铺的基本设置
     */
    public function mgdiscount_store()
    {
        $config_model = model('config');
        //当前的和系统设置的会员等级进行比对
        if (!request()->isPost()) {
            $list_setting = rkcache('config', true);
            $this->assign('list_setting', $list_setting);
            $this->assign('mgdiscount_store_arr', $this->_get_mgdiscount_arr($list_setting['store_mgdiscount']));
            $this->setAdminCurItem('mgdiscount_store');
            return $this->fetch();
        } else {

            $member_model = model('member');
            //系统等级设置
            $membergrade_arr = $member_model->getMemberGradeArr();

            
            $result_1 = array();
            $pre_level_discount = 0;
            foreach ($membergrade_arr as $key => $value) {
                $current_level_discount = floatval($_POST['mgdiscount_store'][$key]['level_discount'] * 10);
                
                //限制会员等级高的会员享受更低折扣
                if($pre_level_discount==0){
                    $pre_level_discount = $current_level_discount;
                }
                if($current_level_discount>$pre_level_discount){
                    $this->error(sprintf(lang('current_level_discount_error'),$value['level_name'],$pre_level_discount/10));
                }
                $pre_level_discount = $current_level_discount;
                    
                if ($current_level_discount < 1 || $current_level_discount > 100) {
                    $this->error(lang('current_level_discount_range_error'));
                }
                
                $result_1[$key]['level_discount'] = $current_level_discount / 10;
                $result_1[$key]['level_name'] = $value['level_name'];
            }
            
            $update_array['store_mgdiscount']=serialize($result_1);
            
            
            $result = $config_model->editConfig($update_array);
            if ($result) {
                $this->log(lang('ds_inviter_set'),1);
                $this->success(lang('ds_common_op_succ'), 'Promotionmgdiscount/mgdiscount_store');
            }else{
                $this->log(lang('ds_inviter_set'),0);
                $this->error(lang('ds_common_op_fail'));
            }
        }
    }

    //显示不同商品享受的会员等级折扣
    public function mgdiscount_goods()
    {

        $goods_model = model('goods');
        $condition['goods_mgdiscount'] = array('neq', '');
        $goods_list = $goods_model->getGoodsCommonOnlineList($condition);

        foreach ($goods_list as $key => $goods) {
            $goods_list[$key]['goods_mgdiscount_arr'] = $this->_get_mgdiscount_arr($goods['goods_mgdiscount']);
        }


        $this->assign('show_page', $goods_model->page_info->render());
        $this->assign('goods_list', $goods_list);

        $this->setAdminCurItem('mgdiscount_goods');
        return $this->fetch();
    }

    /**
     * 通过系统会员等级和现有数据比对得出数值
     * @param type $mgdiscount_arr_temp
     * @return type
     */
    private function _get_mgdiscount_arr($mgdiscount_arr_temp)
    {
        $mgdiscount_arr_temp = @unserialize($mgdiscount_arr_temp);

        $member_model = model('member');
        //系统等级设置
        $membergrade_arr = $member_model->getMemberGradeArr();

        $mgdiscount_arr = array();
        foreach ($membergrade_arr as $key => $value) {
            $mgdiscount_arr[$key] = $value;
            $mgdiscount_arr[$key]['level_discount'] = isset($mgdiscount_arr_temp[$key]['level_discount'])?$mgdiscount_arr_temp[$key]['level_discount']:10;
        }
        return $mgdiscount_arr;
    }

    //新增现有商品的折扣
    public function mgdiscount_goods_add()
    {
        $member_model = model('member');
        //系统等级设置
        $membergrade_arr = $member_model->getMemberGradeArr();
        if (!request()->isPost()) {
            $this->assign('mgdiscount_goods_arr', $membergrade_arr);
            $this->setAdminCurItem('mgdiscount_goods_add');
            return $this->fetch('mgdiscount_goods_add');
        } else {


            //获取提交的数据
            $goods_id = intval(input('post.mgdiscount_goods_id'));
            if (empty($goods_id)) {
                ds_json_encode(10001,lang('param_error'));
            }
            $goods_model = model('goods');
            $goods_info = $goods_model->getGoodsInfoByID($goods_id);
            if (empty($goods_info)) {
                ds_json_encode(10001,lang('param_error'));
            }


            $data = array();
            $pre_level_discount = 0;
            foreach ($membergrade_arr as $key => $value) {
                $current_level_discount = intval($_POST['mgdiscount_goods'][$key]['level_discount'] * 10);
                
                //限制会员等级高的会员享受更低折扣
                if($pre_level_discount==0){
                    $pre_level_discount = $current_level_discount;
                }
                if($current_level_discount>$pre_level_discount){
                    ds_json_encode(10001,sprintf(lang('current_level_discount_error'),$value['level_name'],$pre_level_discount/10));
                }
                $pre_level_discount = $current_level_discount;
                
                if ($current_level_discount < 1 || $current_level_discount > 100) {
                    ds_json_encode(10001,lang('current_level_discount_range_error'));
                }
                $data[$key]['level_discount'] = $current_level_discount / 10;
                $data[$key]['level_name'] = $value['level_name'];
            }

            $condition = array();
            $condition['goods_commonid'] = $goods_info['goods_commonid'];
            $result = $goods_model->editGoodscommon(array('goods_mgdiscount' => serialize($data)), $condition);
            $result1 = $goods_model->editGoods(array('goods_mgdiscount' => serialize($data)), $condition);
            

            if ($result&&$result1) {
                $this->log('添加会员等级折扣，公共商品ID：' . $goods_info['goods_commonid'],1);
                ds_json_encode(10000,lang('mgdiscount_add_success'));
            } else {
                ds_json_encode(10001,lang('mgdiscount_add_fail'));
            }
        }
    }

    function mgdiscount_goods_edit()
    {
        //获取提交的数据
        $goods_commonid = intval(input('param.goods_commonid'));
        if (empty($goods_commonid)) {
            ds_json_encode(10001,lang('param_error'));
        }

        $goods_model = model('goods');
        $goodscommon_info = $goods_model->getGoodsCommonInfoByID($goods_commonid);
        if (empty($goodscommon_info)) {
            ds_json_encode(10001,lang('goods_not_exist'));
        }

        if (!request()->isPost()) {
            $this->assign('goodscommon_info', $goodscommon_info);
            $this->assign('mgdiscount_goods_arr', $this->_get_mgdiscount_arr($goodscommon_info['goods_mgdiscount']));
            $this->setAdminCurItem('mgdiscount_goods_edit');
            return $this->fetch('mgdiscount_goods_add');
        } else {

            $member_model = model('member');
            //系统等级设置
            $membergrade_arr = $member_model->getMemberGradeArr();

            $data = array();
            
            $pre_level_discount = 0;
            foreach ($membergrade_arr as $key => $value) {
                $current_level_discount = floatval($_POST['mgdiscount_goods'][$key]['level_discount'] * 10);
                
                //限制会员等级高的会员享受更低折扣
                if($pre_level_discount==0){
                    $pre_level_discount = $current_level_discount;
                }
                if($current_level_discount>$pre_level_discount){
                    ds_json_encode(10001,sprintf(lang('current_level_discount_error'),$value['level_name'],$pre_level_discount/10));
                }
                $pre_level_discount = $current_level_discount;
                
                if ($current_level_discount < 1 || $current_level_discount > 100) {
                    ds_json_encode(10001,lang('current_level_discount_range_error'));
                }
                $data[$key]['level_discount'] = $current_level_discount / 10;
                $data[$key]['level_name'] = $value['level_name'];
            }

            $condition = array();
            $condition['goods_commonid'] = $goods_commonid;
            $result = $goods_model->editGoodscommon(array('goods_mgdiscount' => serialize($data)), $condition);
            $result1 = $goods_model->editGoods(array('goods_mgdiscount' => serialize($data)), $condition);

            if ($result && $result1) {
                 $this->log('添加会员等级折扣，公共商品ID：' . $goods_commonid,1);
                ds_json_encode(10000,lang('mgdiscount_add_success'));
            } else {
                ds_json_encode(10001,lang('mgdiscount_add_fail'));
            }
        }
    }

    /**
     * 删除
     */
    public function mgdiscount_del()
    {
        $goods_commonid = intval(input('param.goods_commonid'));

        if (empty($goods_commonid)) {
            ds_json_encode(10001,lang('param_error'));
        }

        $condition = array();
        $condition['goods_commonid'] = $goods_commonid;

        $goods_model = model('goods');
        $result = $goods_model->editGoodscommon(array('goods_mgdiscount' => ''), $condition);
        $result1 = $goods_model->editGoods(array('goods_mgdiscount' => ''), $condition);

        if ($result && $result1) {
            ds_json_encode(10000,lang('ds_common_op_succ'));
        } else {
            ds_json_encode(10001,lang('ds_common_op_fail'));
        }
    }

    
    /**
     * 选择活动商品
     * */
    public function search_goods() {
        $goods_model = model('goods');
        $condition = array();
        $condition['goods_name'] = array('like', '%' . input('param.goods_name') . '%');
        $goods_list = $goods_model->getGoodsCommonListForPromotion($condition, '*', 8, 'groupbuy');
        $this->assign('goods_list', $goods_list);
        $this->assign('show_page', $goods_model->page_info->render());
        echo $this->fetch('search_goods');
        exit;
    }

    public function mgdiscount_goods_info() {
        $goods_commonid = intval(input('param.goods_commonid'));

        $data = array();
        $data['result'] = true;

        //判断此商品是否已经参加会员等级折扣，
        $result = $this->_check_allow_mgdiscount($goods_commonid);
        if($result['result'] != TRUE){
            echo json_encode($result);
            die;
        }
        
        //获取商品具体信息用于显示
        $goods_model = model('goods');
        $condition = array();
        $condition['goods_commonid'] = $goods_commonid;
        $goods_list = $goods_model->getGoodsOnlineList($condition);

        if (empty($goods_list)) {
            $data['result'] = false;
            $data['message'] = lang('param_error');
            echo json_encode($data);
            die;
        }


        $goods_info = $goods_list[0];
        $data['goods_id'] = $goods_info['goods_id'];
        $data['goods_name'] = $goods_info['goods_name'];
        $data['goods_price'] = $goods_info['goods_price'];
        $data['goods_image'] = goods_thumb($goods_info, 240);
        $data['goods_href'] = url('Goods/index', array('goods_id' => $goods_info['goods_id']));

        echo json_encode($data);
        die;
    }

    /*
     * 判断此商品是否已经参加拼团
     */
    private function _check_allow_mgdiscount($goods_commonid) {
        $condition = array();
        $goodscommon_info = model('goods')->getGoodsCommonInfoByID($goods_commonid);
        $result['result'] = TRUE;
        if ($goodscommon_info['goods_mgdiscount'] != '') {
            $result['result'] = FALSE;
            $result['message'] = lang('goods_discount_already_set');
        }
        return $result;
    }



    
   /**
     * 页面内导航菜单
     *
     * @param string $menu_key 当前导航的menu_key
     * @param array $array 附加菜单
     * @return
     */
    protected function getAdminItemList() {
        $menu_array = array(
            array(
                'name' => 'mgdiscount_store',
                'text' => lang('mgdiscount_store'),
                'url' => url('Promotionmgdiscount/mgdiscount_store')
            ), array(
                'name' => 'mgdiscount_goods',
                'text' => lang('mgdiscount_goods'),
                'url' => url('Promotionmgdiscount/mgdiscount_goods')
            ),
            array(
                'name' => 'mgdiscount_goods_add',
                'text' => lang('mgdiscount_goods_add'),
                'url' => url('Promotionmgdiscount/mgdiscount_goods_add')
            ),
        );
        return $menu_array;
    }
}